package com.qianyitian.hope2.spider.fetcher;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.Resources;
import com.qianyitian.hope2.spider.config.PropertyConfig;
import com.qianyitian.hope2.spider.model.KLineInfo;
import com.qianyitian.hope2.spider.model.Stock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

@Component("guguDataWebStockRetreiver")
public class GuguDataWebStockRetreiver extends WebStockRetreiver {
    @Autowired
    PropertyConfig propertyConfig;

    private Logger logger = LoggerFactory.getLogger(getClass());
    //    DataStatus: {
//        RequestParameter: "symbol=BABA&beginDate=20200101&endDate=20210101",
//                StatusCode: 100,
//                StatusDescription: "请求成功",
//                ResponseDateTime: "2021-01-16 20:50:44",
//                DataTotalCount: 252
//    },
//    Data: [
//    {
//        Symbol: "BABA",
//                TimeKey: 20200102,
//            Open: 216.6,
//            Close: 219.77,
//            High: 219.98,
//            Low: 216.54,
//            Volume: 15873500
//    }
    String US_URL = "https://api.gugudata.com/stock/us?appkey={0}&symbol={1}&beginDate={2}&endDate={3}&adjust=pre";
    String HK_URL = "https://api.gugudata.com/stock/hk?appkey={0}&symbol={1}&beginDate={2}&endDate={3}&adjust=pre";

    @Override
    public Stock fetchStockInfo(Stock stock) throws IOException {
        stock.setkLineType(Stock.TYPE_DAILY);
        String symbol = stock.getCode();
        String urlFormat = null;
        String appkey = null;
        if (stock.getMarket().equalsIgnoreCase("US")) {
            urlFormat = US_URL;
            appkey = propertyConfig.getGugudataAPIKeyUS();
            return readUS(stock, symbol, urlFormat, appkey);
        } else {
            urlFormat = HK_URL;
            appkey = propertyConfig.getGugudataAPIKeyHK();
            return readHK(stock, symbol, urlFormat, appkey);
        }






    }

    private Stock readUS(Stock stock, String symbol, String urlFormat, String appkey) throws IOException {
        int year=LocalDate.now().getYear();
        String url = MessageFormat.format(urlFormat, appkey, symbol, "20180101", year+"1231");
        List<KLineInfo> all = readData(stock, url);
        stock.setkLineInfos(all);
        return stock;
    }

    private Stock readHK(Stock stock, String symbol, String urlFormat, String appkey) throws IOException {
        //这家的api很破，港股一次只能取一年的
        int startYear=2019;
        int endYear=LocalDate.now().getYear();
        List<KLineInfo> all = new LinkedList<>();
        for (int  i= startYear; i <= endYear; i++) {
            String url = MessageFormat.format(urlFormat, appkey, symbol, i+"0101", i+"1231");
            List<KLineInfo> appendList = readData(stock, url);
            all.addAll(appendList);
        }
        stock.setkLineInfos(all);
        return stock;
    }

    @Override
    public Stock fetchIndexInfo(Stock code) throws IOException {
        throw new RuntimeException("not implemented");
    }

    @Override
    public String fetchFundsInfo(String code) throws IOException {
        throw new RuntimeException("not implemented");
    }

    protected List<KLineInfo> readData(Stock stock, String url) throws IOException {
        List<KLineInfo> kLineInfos = new LinkedList<KLineInfo>();
        try {
            URL neteaseUrl = new URL(url);
            String content = Resources.asCharSource(neteaseUrl, Charset.forName("UTF-8")).readFirstLine();
            JSONObject jsonObject = JSON.parseObject(content);


            if(jsonObject.getJSONArray("Data")==null){
                String error=jsonObject.getObject("DataStatus",JSONObject.class).getString("StatusDescription");
                String url1=jsonObject.getObject("DataStatus",JSONObject.class).getString("RequestParameter");
                logger.error(error + url1);
                return null;
            }
            jsonObject.getJSONArray("Data").stream().forEach(obj -> {
                JSONObject kInfo = (JSONObject) obj;

                String dateString = kInfo.getString("TimeKey");
                double open = kInfo.getDouble("Open");
                double close = kInfo.getDouble("Close");
                double low = kInfo.getDouble("Low");
                double high = kInfo.getDouble("High");
                int volume = kInfo.getIntValue("Volume");
                double turnoverRate=kInfo.getDouble("TurnoverRate");

                KLineInfo daily = new KLineInfo();
                LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE);
                daily.setOpen(open);
                daily.setHigh(high);
                daily.setLow(low);
                daily.setClose(close);
                daily.setDate(date);
                daily.setVolume(volume);
                daily.setTurnoverRate(turnoverRate);
                kLineInfos.add(daily);
            });
        } catch (IOException e) {
            logger.error("retrieve gugudata stock data error for " + url, e);
            throw e;
        }
        return kLineInfos;
    }
}
